package cn.org.gs.filelock;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileLockDemo {
    // 把input中的内容添加到文件追加到1.txt中
    public static void main(String[] args) throws Exception{
        String input = "atguigu";
        System.out.println("input : " + input);

        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath = "d:\\1.txt";
        Path path = Paths.get(filePath);
        FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE,
                StandardOpenOption.APPEND);
        channel.position(channel.size() - 1);

        // 锁开始的地方和锁的范围
        FileLock lock = channel.tryLock(0, Long.MAX_VALUE, false);
        System.out.println("共享锁：" + lock.isShared());

        channel.write(buffer);
        channel.close();
        System.out.println("写操作完成！");

        readFile(filePath);
    }

    private static void readFile(String filePath) throws Exception{
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String readLine = bufferedReader.readLine();
        System.out.println("读取内容：");
        while (readLine != null){
            System.out.println(" " + readLine);
            readLine = bufferedReader.readLine();
        }

        fileReader.close();
        bufferedReader.close();
    }
}
